package arity.calculator.plus;

import calculator.Defs;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;

public class ShowDefinitionsListFragment extends ListFragment
{
	public interface DefinitionsProvider
	{
		Defs getDefinitions();
	}
	
	private Defs mDefinitions = null;
	private ArrayAdapter<String> mAdapter = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);	
		
		DefinitionsProvider provider = (DefinitionsProvider) getActivity();
		
		if (provider == null)
			return;
		
		mDefinitions = provider.getDefinitions();
		mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mDefinitions.getLines());
		
		setListAdapter(mAdapter);		
		setHasOptionsMenu(true);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		super.onCreateOptionsMenu(menu, inflater);
		
		inflater.inflate(R.menu.defs, menu);
	}
	
	@Override
	public void onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);
		
		MenuItem item = menu.findItem(R.id.clear_defs);
		
		if (item != null)
			item.setEnabled(mDefinitions.size() > 0);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.clear_defs)
		{
			mDefinitions.clear();
			mDefinitions.save();
				
			mAdapter.notifyDataSetInvalidated();
			
			return true;
		}
		
		return (super.onOptionsItemSelected(item));
	}
}
